import { useRequestHandle } from '@/utils/utils';
import { Card, Badge, Button } from 'antd';
import { useMatch ,history} from 'umi';
import { getById, getPublishFlowById, getHealthy, surePublish } from './service';
import { useEffect, useState } from 'react';
import { useUpdateEffect } from '@umijs/hooks';
import { Space } from 'antd';
import SurePublish from "./components/SurePublish";
import { RollbackOutlined } from '@ant-design/icons';



export default () => {
  const match = useMatch('/system/developer/applications/restore/:id');
  const id = match?.params.id;
  const [serverConfig, setServerConfig] = useState({});
  const [publishFlow, setPublishFlow] = useState({});
  const [healthy, setHealthy] = useState(false);
  const [current, setCurrent] = useState(0);
  const getHealthyRequest = useRequestHandle(getHealthy, () => {
    setHealthy(true);
  });

  const surePublishRequest = useRequestHandle(surePublish, () => {
    setCurrent(current + 1);
  });

  const getHealthyCheck = () => {


    if (getHealthyRequest.loading) {
      return <Badge status="processing" text="检查中" />
    }

    if (healthy) {
      return <Badge status="success" text="服务器在线" />
    }

    return <Badge status="error" text="服务器离线" />




  }
  useEffect(() => {
    async function init() {

      const r1 = await getPublishFlowById({ id })
      setPublishFlow(r1.data);
      const response = await getById({ id: r1.data.agentServerConfigId });
      if (response && response.success) {
        setServerConfig(response.data);
      }
    }
    init();
  }, [id])
  useUpdateEffect(() => {
    if (serverConfig.id) {
      getHealthyRequest.run({ id: serverConfig.agentServerId });
    }
  }, [serverConfig]);
  useUpdateEffect(() => {
    if (publishFlow.id) {
      setCurrent(publishFlow.nodes.length);
    }
  }, [publishFlow])
  return (
    <>
      <Card title={<Space >
        <Button type='link' size='small'
        onClick={() => {
          history.push("/system/developer/applications/publishflow");
        }}
        icon={<RollbackOutlined />}>返回</Button>
        {serverConfig.agentServer?.serverName}
        {serverConfig.serverName}
        {getHealthyCheck()}
      </Space>}>
        <SurePublish
          id={id}
          loading={surePublishRequest.loading}
          onSuccess={() => {
            surePublishRequest.run({ id: publishFlow.id });
          }} record={serverConfig} publishFlow={publishFlow} />



      </Card>
    </>
  );
};
